package com.sugon.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.sugon.dao.ToolsBaseDao;
import com.sugon.dao.ToolsControlWayDao;
import com.sugon.dao.ToolsTypeDao;
import com.sugon.entity.SysMsgEntity;
import com.sugon.entity.ToolsBaseEntity;
import com.sugon.entity.ToolsControlWayEntity;
import com.sugon.entity.ToolsTypeEntity;
import com.sugon.service.SysMsgService;
import com.sugon.service.SysProcessInfoService;
import com.sugon.service.ToolsBaseService;
import com.sugon.utils.ProcessInfoEnum;
import com.sugon.utils.ShiroUtils;
import com.sugon.utils.excel.ExcelImport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 工装清单管理Service实现类
 *
 * @author sugon
 * @date 2019-08-01 16:42:44
 */
@Service("ToolsBaseService")
public class ToolsBaseServiceImpl implements ToolsBaseService {

    @Autowired
    private ToolsBaseDao toolsBaseDao;
    @Autowired
    private ToolsTypeDao toolsTypeDao;
    @Autowired
    private ToolsControlWayDao toolsControlWayDao;
    @Autowired
    private SysProcessInfoService sysProcessInfoService;
    @Autowired
    private SysMsgService sysmsgService;

    @Override
    public ToolsBaseEntity queryObject(String id) {
        return toolsBaseDao.queryObject(id);
    }

    @Override
    public ToolsBaseEntity queryList(String mapNo, String createNo, String type) {
        List<ToolsBaseEntity> toolsBaseList;
        Map<String, Object> param;
        if (StrUtil.isNotEmpty(mapNo)) {
            param = new HashMap<>(1);
            param.put("mapNo", mapNo.trim());
            toolsBaseList = queryList(param);
            if (CollectionUtil.isNotEmpty(toolsBaseList)) {
                return toolsBaseList.get(0);
            }
        }
        if (StrUtil.isNotEmpty(createNo)) {
            param = new HashMap<>(1);
            param.put("createNo", createNo.trim());
            toolsBaseList = queryList(param);
            if (CollectionUtil.isNotEmpty(toolsBaseList)) {
                return toolsBaseList.get(0);
            }
        }
        if (StrUtil.isNotEmpty(type)) {
            param = new HashMap<>(1);
            param.put("type", type.trim());
            toolsBaseList = queryList(param);
            if (CollectionUtil.isNotEmpty(toolsBaseList)) {
                return toolsBaseList.get(0);
            }
        }
        return null;
    }

    @Override
    public List<ToolsBaseEntity> queryList(Map<String, Object> map) {
        return toolsBaseDao.queryList(map);
    }

    @Override
    public int queryTotal(Map<String, Object> map) {
        return toolsBaseDao.queryTotal(map);
    }

    @Override
    public int save(ToolsBaseEntity ToolsBase) {
        ToolsBase.setId(RandomUtil.randomString(32));
//        ToolsBase.setToolsCode(generateUniqueCode());
//        ToolsBase.setWorkshop(StrUtil.sub(ToolsBase.getProductLine(), 0, 4));
        ToolsBase.setCreateTime(DateUtil.date());
        ToolsBase.setCreateUser(ShiroUtils.getUserId());
        ToolsBase.setUpdateUser(ToolsBase.getCreateUser());
        ToolsBase.setUpdateTime(ToolsBase.getCreateTime());
        ToolsBase.setStockNum(0);
        ToolsBase.setScrapNum(0);
        ToolsBase.setTransitNum(0);
        sysProcessInfoService.saveProcessInfo(ToolsBase.getId(), ProcessInfoEnum.TLS_GZML, 0, null);
        int rows = toolsBaseDao.save(ToolsBase);
        if (rows > 0) {
            SysMsgEntity msgEntity = new SysMsgEntity();
            String Id = ToolsBase.getId();
            msgEntity.setDataId(Id);
            msgEntity.setDataUrl("../tools/ToolsBase.html?Id=" + Id);
            sysmsgService.addApproveItem(ProcessInfoEnum.TLS_GZML, msgEntity, 0);
        }
        return rows;
    }

    @Override
    public int update(ToolsBaseEntity ToolsBase) {
        ToolsBase.setUpdateTime(DateUtil.date());
        ToolsBase.setUpdateUser(ShiroUtils.getUserId());
        // 设置车间ID
//        ToolsBase.setWorkshop(StrUtil.sub(ToolsBase.getProductLine(), 0, 4));

//        if (ToolsBase.getReviewStatus() != 0) {
//            sysProcessInfoService.saveProcessInfo(ToolsBase.getId(), ProcessInfoEnum.TLS_GZML, 0, null);
//        }
//        //修改内容后，需重新进行审批
//        ToolsBase.setReviewStatus(0);
        int rows = toolsBaseDao.update(ToolsBase);
        if (rows > 0) {
            SysMsgEntity msgEntity = new SysMsgEntity();
            String Id = ToolsBase.getId();
            msgEntity.setDataId(Id);
            msgEntity.setDataUrl("../tools/ToolsBase.html?Id=" + Id);
            sysmsgService.addApproveItem(ProcessInfoEnum.TLS_GZML, msgEntity, 0);
        }
        return rows;
    }

    @Override
    public int delete(String id) {
        return toolsBaseDao.delete(id);
    }

    @Override
    public int deleteBatch(String[] ids) {
        return toolsBaseDao.deleteBatch(ids);
    }

    @Override
    public int importE(MultipartFile file) {
        List<String[]> list = ExcelImport.getExcelData(file);
        int count = 0;
        // 每行导入的内容应该包含的列数
        int cols = 13;
        if (CollectionUtil.isNotEmpty(list)) {
            for (int i = 0; i < list.size(); i++) {
                ToolsBaseEntity toolsBase = null;
                int size = i + 1;
                if (size < list.size()) {
                    String[] array = list.get(size);
                    if (ArrayUtil.isNotEmpty(array) && array.length < cols) {
                        array = ArrayUtil.resize(array, cols);
                    }
                    // 如果工装基础信息已填写则更新，否则新增
                    if (StrUtil.isNotEmpty(array[1])) {
                        toolsBase = toolsBaseDao.queryObject(array[1]);
                    }
                    if (toolsBase == null) {
                        toolsBase = new ToolsBaseEntity();
                    }
                    toolsBase.setName(array[0]);
                    toolsBase.setErpCode(array[2]);
                    toolsBase.setMapNo(array[3]);
                    toolsBase.setCreateNo(array[4]);
                    toolsBase.setType(array[5]);
                    toolsBase.setApplicableModel(array[6]);
                    // 设置工装类别
                    ToolsTypeEntity toolsType = getByTypeName(array[7]);
                    if (toolsType != null) {
                        toolsBase.setToolsType(toolsType.getTypeCode());
                    }
                    // 是否是易损件
                    toolsBase.setIsVulnerable("是".equals(array[8]) ? 1 : 0);
                    // 设置管控方式
                    if (StrUtil.isNotEmpty(array[9])) {
                        String controlCode = "";
                        String[] controlNames = array[9].split(",");
                        for (String controlName : controlNames) {
                            ToolsControlWayEntity toolsControlWay = getByControlName(controlName);
                            if (toolsControlWay != null) {
                                controlCode += "," + toolsControlWay.getControlCode();
                            }
                        }
                        toolsBase.setControlWay(controlCode.replaceFirst(",", ""));
                    } else {
                        toolsBase.setControlWay("");
                    }
                    // 设置备注
                    toolsBase.setRemark(array[10]);
                    if (StrUtil.isNotEmpty(toolsBase.getId())) {
                        count += update(toolsBase);
                    } else {
                        count += save(toolsBase);
                    }
                }
            }
        }
        return count;
    }

    /**
     * 根据类别名称获取工装类别
     *
     * @param typeName
     * @return
     */
    private ToolsTypeEntity getByTypeName(String typeName) {
        Map<String, Object> param = new HashMap<>(1);
        param.put("typeName", typeName);
        List<ToolsTypeEntity> toolsTypes = toolsTypeDao.queryList(param);
        return CollectionUtil.isNotEmpty(toolsTypes) ? toolsTypes.get(0) : null;
    }

    private ToolsControlWayEntity getByControlName(String controlName) {
        Map<String, Object> param = new HashMap<>(1);
        param.put("name", controlName);
        List<ToolsControlWayEntity> toolsTypes = toolsControlWayDao.queryList(param);
        return CollectionUtil.isNotEmpty(toolsTypes) ? toolsTypes.get(0) : null;
    }

}
